#[macro_use] extern crate structopt;
extern crate usrtrust;

use structopt::StructOpt;
use usrtrust::{CPBuffer,Mem,CMem,Fifo,Log,Environment,ULogs};
use std::path::{Path,PathBuf};
use std::io::Write;
use std::{thread, time};
use std::sync::mpsc;

#[derive(Debug, StructOpt)]
#[structopt(name = "MayApp", about = "An example of StructOpt usage.")]
struct Opt {
    #[structopt(short = "f"
        , long = "file"
        , default_value="c349e642-6b66-5eaf-a82a-369a5cb5b9c5"
        , parse(from_str)
    )]
    file: String,
}

fn main() -> std::io::Result<()> {
    let opt = Opt::from_args();
    println!("{}",std::mem::size_of::<CPBuffer>());
    let mut path = PathBuf::new();
    path.push("/tmp/usrtos");
    path.push(opt.file);
    let p = path.into_os_string().into_string().unwrap();

    let mut log_s = Log::attach(p.clone(),2)?;

    let (tx,rx) = mpsc::channel();

    let logout = thread::spawn(move || {
        let mut log_r = Log::attach(p.clone(),2).unwrap();
        log_r.reset();
        loop {
            let sig = rx.recv_timeout(time::Duration::from_millis(500)); 
            match sig {
                Err(mpsc::RecvTimeoutError::Timeout) => {
                    log_r.dump();
                },
                _default => {break;},
            }
        }
    });
    
    for i in 0..4 {
        writeln!(log_s,"this is {}",i);
    }
    log_s.flush()?;
    thread::sleep(time::Duration::from_millis(1000));
    tx.send(0).unwrap();
    logout.join();
    Ok(())
}
